


<template>
	<mescroll-uni @init="mescrollInit" :up="upOption" :down="downOption" @down="downCallback" @up="upCallback">
		<view class="content">
			<view :style='{"minHeight":"100%","width":"100%","padding":"0 30rpx","position":"relative","background":"#F3F3F3","height":"auto"}'>
				<!-- <view class="page-title" :style='{"padding":"30rpx 0 10rpx","fontSize":"40rpx","color":"#333","textAlign":"center","fontWeight":"bold"}'>互助需求预约</view> -->
				<view class="page-title" :style='{"padding":"30rpx 0 10rpx","fontSize":"40rpx","color":"#333","textAlign":"center","fontWeight":"bold"}'>我的预约</view>

				<view class="cu-bar bg-white search" :style='{"padding":"30rpx 0 20rpx 0","margin":"0","background":"none","display":"flex","width":"100%","position":"relative","height":"auto"}'>
					<view :style='{"border":"none","margin":"0","borderRadius":"20rpx","flex":"1","background":"#fff","lineHeight":"100rpx","position":"relative","height":"100rpx"}' class="search-form round">
						<text class="icon iconfont icon-fangdajing07" :style='{"color":"rgb(153, 153, 153)","left":"0px","textAlign":"center","width":"100rpx","fontSize":"50rpx","lineHeight":"100rpx","position":"absolute","right":"0px"}'></text>
						<input placeholder-style="color: #666; font-size: 34rpx;" :style='{"border":"0","padding":"20rpx 20rpx 20rpx 100rpx","color":"#333","borderRadius":"50rpx","background":"none","width":"100%","lineHeight":"60rpx","fontSize":"34rpx","height":"100rpx"}' v-model="searchForm.title" type="text" placeholder="请输入需求标题关键词" ></input>
					</view>
					<button :style='{"border":"0","padding":"0px","margin":"0","color":"#fff","right":"4rpx","borderRadius":"50rpx","top":"30rpx","background":"linear-gradient( 135deg, #9EEEEB 0%, #99ABFF 100%)","width":"160rpx","lineHeight":"100rpx","fontSize":"34rpx","position":"absolute","height":"100rpx","fontWeight":"bold"}' @tap="search" class="cu-btn shadow-blur round">搜索</button>
				</view>
			
				<view class="sort-section" :style='{"padding":"20rpx 0","margin":"20rpx 0 30rpx","borderRadius":"12rpx","background":"#fff","width":"100%"}'>
					<view class="section-title" :style='{"fontSize":"36rpx","color":"#333","margin":"0 0 20rpx 30rpx","fontWeight":"bold"}'>排序方式</view>
					<view :style='{"flexWrap":"wrap","margin":"10rpx 0 10rpx 30rpx","display":"flex"}'>
						<view @click="sortClick('addtime')" :style='{"border":"2rpx solid #999","padding":"0 20rpx","margin":"0 30rpx 0 0","outline":"0","borderRadius":"12rpx","background":"#fff","display":"flex","height":"70rpx","alignItems":"center"}'>
							<text :style='{"color":"#333","lineHeight":"70rpx","fontSize":"32rpx"}'>按日期</text>
							<text v-if="listSort!='addtime'" class="icon iconfont icon-shijian18" :style='{"margin":"0 0 0 10rpx","lineHeight":"70rpx","fontSize":"32rpx","color":"#999"}'></text>
							<text v-else-if="listSort=='addtime'&&listOrder=='asc'" class="icon iconfont icon-shijian18" :style='{"margin":"0 0 0 10rpx","lineHeight":"70rpx","fontSize":"32rpx","color":"#5ba6df"}'></text>
							<text v-else-if="listSort=='addtime'&&listOrder=='desc'" class="icon iconfont icon-shijian18" :style='{"margin":"0 0 0 10rpx","lineHeight":"70rpx","fontSize":"32rpx","color":"#5ba6df"}'></text>
						</view>
					</view>
				</view>

				<view :style='{"width":"100%","background":"none","flexDirection":"column","display":"flex","height":"auto"}'>
					<view v-for="(appointment, index) in list" :key="index" class="appointment-item" :style='{"boxShadow":"0 5rpx 20rpx rgba(0,0,0,.2)","margin":"0 0 40rpx","backgroundColor":"#fff","borderRadius":"20rpx","padding":"30rpx","width":"100%"}'>
						<view class="appointment-header" :style='{"display":"flex","alignItems":"center","justifyContent":"space-between"}'>
							<image :style='{"width":"100rpx","height":"100rpx","borderRadius":"10rpx"}' :src="appointment.picture" mode="aspectFill"></image>
							<view class="appointment-info" :style='{"flex":"1","paddingLeft":"20rpx"}'>
								<view class="appointment-title" :style='{"fontSize":"36rpx","color":"#333","fontWeight":"bold"}'>{{appointment.title}}</view>
								<view :style='{"color":"#666","fontSize":"28rpx","marginTop":"10rpx"}'>编号: {{appointment.yuyuehao}}</view>
							</view>
							<view class="appointment-status" :style='{"padding":"4rpx 20rpx","background":appointment.status === "已处理" ? "#4CD964" : (appointment.status === "待处理" ? "#F0AD4E" : "#1296DB"),"color":"#fff","borderRadius":"30rpx","fontSize":"28rpx"}'>{{appointment.status}}</view>
						</view>
						<view class="appointment-venue" :style='{"marginTop":"20rpx","color":"#888","fontSize":"32rpx"}'>需求描述: {{appointment.address}}</view>
						<view class="appointment-time" :style='{"marginTop":"10rpx","color":"#888","fontSize":"28rpx"}'>发布时间: {{appointment.fabushijian}}</view>
						<view class="appointment-points" :style='{"marginTop":"10rpx","color":"#5ba6df","fontSize":"28rpx","fontWeight":"bold"}'>积分: {{appointment.jifen}}</view>
						<view class="appointment-actions" :style='{"display":"flex","marginTop":"20rpx","justifyContent":"flex-end"}'>
							<button @tap="viewAppointment(appointment)" :style='{"margin":"0 10rpx","padding":"0 30rpx","background":"#4CD964","color":"#fff","borderRadius":"10rpx","fontSize":"28rpx","lineHeight":"70rpx","height":"70rpx"}'>查看</button>
							<button @tap="editAppointment(appointment)" :style='{"margin":"0 10rpx","padding":"0 30rpx","background":"#1296DB","color":"#fff","borderRadius":"10rpx","fontSize":"28rpx","lineHeight":"70rpx","height":"70rpx"}'>修改</button>
							<button @tap="deleteAppointment(appointment)" :style='{"margin":"0 10rpx","padding":"0 30rpx","background":"#E54D42","color":"#fff","borderRadius":"10rpx","fontSize":"28rpx","lineHeight":"70rpx","height":"70rpx"}'>删除</button>
						</view>
					</view>
				</view>
				
				<button @click="addAppointment" :style='{"border":"0","boxShadow":"0 5rpx 20rpx rgba(0,0,0,.3)","color":"rgb(255, 255, 255)","bottom":"120rpx","right":"30rpx","outline":"none","borderRadius":"50rpx","background":"linear-gradient( 135deg, #9EEEEB 0%, #99ABFF 100%)","width":"160rpx","lineHeight":"80rpx","fontSize":"34rpx","position":"fixed","height":"80rpx","zIndex":"9","fontWeight":"bold"}' class="add-btn">新增</button>
			</view>
		</view>
		
		<!-- 查看详情的modal弹窗 -->
		<view class="modal" v-if="showModal" @tap.stop="showModal=false" :style='{"width":"100%","height":"100%","background":"rgba(0,0,0,0.5)","position":"fixed","zIndex":"9999","top":"0","left":"0"}'>
			<view class="modal-content" @tap.stop :style='{"padding":"30rpx","width":"80%","borderRadius":"10rpx","background":"#fff","position":"relative","zIndex":"1","margin":"20% auto"}'>
				<view class="modal-header" :style='{"padding":"0 0 20rpx","borderBottom":"1px solid #eee"}'>
					<text :style='{"fontSize":"36rpx","fontWeight":"bold","color":"#333"}'>预约详情</text>
					<text class="close-btn" @tap="showModal=false" :style='{"position":"absolute","right":"30rpx","top":"30rpx","fontSize":"36rpx","color":"#999"}'>×</text>
				</view>
				<scroll-view scroll-y :style='{"maxHeight":"60vh","padding":"20rpx 0"}'>
					<view class="modal-item" :style='{"margin":"0 0 20rpx","display":"flex"}'>
						<text :style='{"width":"180rpx","fontSize":"28rpx","color":"#666"}'>预约标题：</text>
						<text :style='{"flex":"1","fontSize":"28rpx","color":"#333","wordBreak":"break-all"}'>{{currentAppointment.title}}</text>
					</view>
					<view class="modal-item" :style='{"margin":"0 0 20rpx","display":"flex"}'>
						<text :style='{"width":"180rpx","fontSize":"28rpx","color":"#666"}'>需求描述：</text>
						<text :style='{"flex":"1","fontSize":"28rpx","color":"#333","wordBreak":"break-all"}'>{{currentAppointment.address}}</text>
					</view>
					<view class="modal-item" :style='{"margin":"0 0 20rpx","display":"flex"}'>
						<text :style='{"width":"180rpx","fontSize":"28rpx","color":"#666"}'>发布时间：</text>
						<text :style='{"flex":"1","fontSize":"28rpx","color":"#333","wordBreak":"break-all"}'>{{currentAppointment.fabushijian}}</text>
					</view>
					<view class="modal-item" :style='{"margin":"0 0 20rpx","display":"flex"}'>
						<text :style='{"width":"180rpx","fontSize":"28rpx","color":"#666"}'>预约状态：</text>
						<text :style='{"flex":"1","fontSize":"28rpx","color":"#333","wordBreak":"break-all"}'>{{currentAppointment.status}}</text>
					</view>
					<view class="modal-item" :style='{"margin":"0 0 20rpx","display":"flex"}'>
						<text :style='{"width":"180rpx","fontSize":"28rpx","color":"#666"}'>积分：</text>
						<text :style='{"flex":"1","fontSize":"28rpx","color":"#333","wordBreak":"break-all"}'>{{currentAppointment.jifen}}</text>
					</view>
					<view class="modal-item" :style='{"margin":"0 0 20rpx","display":"flex","flexDirection":"column"}'>
						<text :style='{"width":"100%","fontSize":"28rpx","color":"#666","marginBottom":"10rpx"}'>服务内容：</text>
						<text :style='{"fontSize":"28rpx","color":"#333","wordBreak":"break-all","lineHeight":"1.5"}'>{{currentAppointment.fuwuneirong || '暂无内容'}}</text>
					</view>
				</scroll-view>
				<view class="modal-footer" :style='{"display":"flex","justifyContent":"flex-end","marginTop":"30rpx","borderTop":"1px solid #eee","paddingTop":"20rpx"}'>
					<button @tap="showModal=false" :style='{"margin":"0 0 0 20rpx","padding":"0 40rpx","background":"#999","color":"#fff","borderRadius":"10rpx","fontSize":"28rpx","lineHeight":"70rpx","height":"70rpx"}'>关闭</button>
				</view>
			</view>
		</view>
	</mescroll-uni>
</template>

<script>
	export default {
		data() {
			return {
				btnColor: ['#409eff','#67c23a','#909399','#e6a23c','#f56c6c','#356c6c','#351c6c','#f093a9','#a7c23a','#104eff','#10441f','#a21233','#503319'],
				list: [],
				userid: '',
				mescroll: null, //mescroll实例对象
				downOption: {
					auto: false //是否在初始化后,自动执行下拉回调callback; 默认true
				},
				upOption: {
					noMoreSize: 5, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
					textNoMore: '~ 没有更多了 ~',
				},
				hasNext: true,
				searchForm:{
					title: '',
				},
				CustomBar: '0',
				listSort: 'id',
				listOrder: 'desc',
				showModal: false,
				currentAppointment: {},
			};
		},
		computed: {
			baseUrl() {
				return this.$base.url;
			},
		},
		async onShow() {
			this.btnColor = this.btnColor.sort(()=> {
				return (0.5-Math.random());
			});
			this.hasNext = true
			// 重新加载数据
			if (this.mescroll) this.mescroll.resetUpScroll()
		},
		async onLoad(options) {
			if(options.userid) {
				this.userid = options.userid;
			} else {
				this.userid = "";
			}
			this.hasNext = true
			// 加载用户预约数据
			// 不在这里调用加载，避免mescroll初始化问题
		},
		methods: {
			// 检查URL是否已包含http前缀
			preHttp(url) {
				return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1;
			},
			
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
				// mescroll初始化完成后自动加载第一页数据
				setTimeout(() => {
					this.mescroll.triggerDownScroll();
				}, 100);
			},
			/*下拉刷新的回调 */
			downCallback(mescroll) {
				this.hasNext = true
				// 重置分页参数页数为1
				mescroll.resetUpScroll()
			},
			/*上拉加载的回调: mescroll携带page的参数, 其中num:当前页 从1开始, size:每页数据条数,默认10 */
			async upCallback(mescroll) {
				// 调用加载用户预约列表
				await this.loadUserAppointments();
			},
			
			// 搜索
			search() {
				// 重置分页并重新加载数据
				this.mescroll.resetUpScroll();
			},
			
			// 排序点击
			sortClick(type) {
				if (this.listSort == type) {
					if (this.listOrder == 'desc') {
						this.listOrder = 'asc'
					} else {
						this.listOrder = 'desc'
					}
				} else {
					this.listSort = type
					this.listOrder = 'desc'
				}
				
				// 重新加载数据，后端排序
				this.mescroll.resetUpScroll();
			},
			
			// 查看预约
			viewAppointment(appointment) {
				// 设置当前预约信息并显示modal弹窗
				this.currentAppointment = appointment;
				this.showModal = true;
			},
			
			// 编辑预约
			editAppointment(appointment) {
				// 导航到编辑页面，编辑页面应该使用update接口
				// 添加状态判断
				  if (appointment.status !== "待处理"&&appointment.status !== "服务中") {
				    uni.showToast({
				      title: '当前状态不可修改',
				      icon: 'none'
				    });
				    return;
				  }
				uni.navigateTo({
					url: `../huzhuxuqiu/add-or-update?id=${appointment.id}`
				});
			},
			
			// 删除预约
			deleteAppointment(appointment) {
				// 添加状态判断：只有"待处理"和"已完成"状态可以删除
								if (appointment.status !== "待处理" && appointment.status !== "已完成") {
									uni.showToast({
										title: '当前状态不允许删除',
										icon: 'none'
									});
									return;
								}
				uni.showModal({
					title: '提示',
					content: '确定要删除该预约吗？',
					success: (res) => {
						if (res.confirm) {
							// 调用删除接口
							uni.request({
								url: this.baseUrl + 'huzhuxuqiuyuyue/delete/' + appointment.id,
								method: 'GET',
								success: (response) => {
									const result = response.data;
									if (result.code === 0) {
										uni.showToast({
											title: '删除成功',
											icon: 'success'
										});
										// 重新加载数据
										this.mescroll.resetUpScroll();
									} else {
										uni.showToast({
											title: result.msg || '删除失败',
											icon: 'none'
										});
									}
								},
								fail: (error) => {
									console.error('删除预约异常:', error);
									uni.showToast({
										title: '网络异常，请稍后重试',
										icon: 'none'
									});
								}
							});
						}
					}
				});
			},
			
			// 新增预约
			addAppointment() {
				uni.navigateTo({
					url: '../huzhuxuqiu/add-or-update'
				});
			},
			
			// 获取用户预约列表
			async loadUserAppointments() {
				// 从本地存储获取当前登录用户信息
				const userSession = uni.getStorageSync("userSession") ? JSON.parse(uni.getStorageSync("userSession")) : null;
				
				if (!userSession) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateTo({
							url: '../login/login'
						});
					}, 1500);
					return;
				}
				
				const zhanghao = userSession.zhanghao;
				
				try {
					const params = {
						page: this.mescroll ? this.mescroll.num : 1,
						limit: this.mescroll ? this.mescroll.size : 10,
						zhanghao: zhanghao,
					};
					
					// 添加搜索条件
					if (this.searchForm.title) {
						params.xuqiubiaoti = '%' + this.searchForm.title + '%';
					}
					
					// 使用原生uni.request代替$api调用
					uni.request({
						url: this.baseUrl + 'huzhuxuqiuyuyue/listByLaoren', // 使用护理预约接口
						method: 'GET',
						data: params,
						success: (response) => {
							const res = response.data;
							
							if (res.code === 0 && res.data && res.data.list) {
								// 如果是第一页数据置空
								if (!this.mescroll || this.mescroll.num === 1) this.list = [];
								
								// 转换数据格式以适应页面展示
								const formattedList = res.data.list.map(item => {
									// 处理图片地址，如果有多张图片，取第一张
									let picturePath = '/static/default.jpg';
									if (item.xuqiuzhaopian) {
										// 处理逗号分隔的多张图片情况
										let pics = item.xuqiuzhaopian.split(',');
										let firstPic = pics[0];
										if (this.preHttp(firstPic)) {
											picturePath = firstPic;
										} else {
											picturePath = this.baseUrl + firstPic;
										}
									}
									
									return {
										id: item.id,
										yuyuehao: item.id.toString(), // 使用ID作为预约号
										title: item.xuqiubiaoti || '未命名预约',
										status: item.fuwuzhuangtai || '待处理',
										address: item.xuqiumiaoshu || '未指定类型',
										fabushijian: item.fabushijian, // 发布时间
										addtime: item.addtime, // 添加时间
										picture: picturePath,
										fuwuneirong: item.fuwuneirong || '',
										jifen: item.jifen || 0 // 积分值
									};
								});
								
								this.list = this.list.concat(formattedList);
								
								// 判断是否还有下一页
								this.hasNext = res.data.list.length === params.limit;
								
								if (this.mescroll) {
									this.mescroll.endSuccess(this.mescroll.size, this.hasNext);
								}
							} else {
								if (this.mescroll) {
									this.mescroll.endErr();
								}
								uni.showToast({
									title: res.msg || '获取预约列表失败',
									icon: 'none'
								});
							}
						},
						fail: (error) => {
							console.error('获取预约列表异常:', error);
							if (this.mescroll) {
								this.mescroll.endErr();
							}
							uni.showToast({
								title: '网络异常，请稍后重试',
								icon: 'none'
							});
						}
					});
				} catch (error) {
					console.error('获取预约列表异常:', error);
					if (this.mescroll) {
						this.mescroll.endErr();
					}
					uni.showToast({
						title: '网络异常，请稍后重试',
						icon: 'none'
					});
				}
			},
		}
	};
</script>

<style lang="scss" scoped>
	.content {
		min-height: calc(100vh - 44px);
		box-sizing: border-box;
		font-size: 34rpx;
	}
	
	.sort-section {
		box-shadow: 0 5rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.appointment-item {
		transition: transform 0.2s;
		
		&:active {
			transform: scale(0.98);
		}
	}
	
	.add-btn {
		transition: all 0.2s;
		
		&:active {
			transform: scale(0.95);
		}
	}
</style> 